#include<func.h>
typedef struct
{
    int tickets;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
}data_t;
void * saler1(void *p)
{
    data_t* d=(data_t*)p;
    while(1)
    {
        pthread_mutex_lock(&d->mutex);
        if(d->tickets>0)
        {
             printf("saler1 start sale %d\n",d->tickets);
             d->tickets--;
             if(d->tickets==0)
             {
                 pthread_cond_signal(&d->cond);

             }
             printf("saler1 finish sale %d\n",d->tickets);
             pthread_mutex_unlock(&d->mutex);
        }
        else{
            pthread_mutex_unlock(&d->mutex);
            break;
        }
        sleep(1);
    }
}

void * saler2(void *p)
{
    data_t* d=(data_t*)p;
    while(1)
    {
        pthread_mutex_lock(&d->mutex);
        if(d->tickets>0)
        {
             printf("saler2 start sale %d\n",d->tickets);
             d->tickets--;
             if(d->tickets==0)
             {
                 pthread_cond_signal(&d->cond);

             }
             printf("saler2 finish sale %d\n",d->tickets);
             pthread_mutex_unlock(&d->mutex);
        }
        else{
            pthread_mutex_unlock(&d->mutex);
            break;
        }
        sleep(1);
    }
}
void * settickets(void *p)
{
    data_t* d=(data_t*)p;
    pthread_mutex_lock(&d->mutex);
    if(d->tickets>0)
    {
        pthread_cond_wait(&d->cond,&d->mutex);

    }
    d->tickets=10;
    pthread_mutex_unlock(&d->mutex);
    
}
int main()
{
    data_t d;
    d.tickets=20;
    int ret=pthread_mutex_init(&d.mutex,NULL);
    THREAD_ERR_CHECK(ret,"pthread_mutex_init");
    ret=pthread_cond_init(&d.cond,NULL);
    THREAD_ERR_CHECK(ret,"pthread_cond_init");
    pthread_t pthid[3];
    ret=pthread_create(&pthid[0],NULL,saler1,&d);
    THREAD_ERR_CHECK(ret,"pthread_create1");
    ret=pthread_create(&pthid[1],NULL,saler2,&d);
    THREAD_ERR_CHECK(ret,"pthread_create2");
    ret=pthread_create(&pthid[2],NULL,settickets,&d);
    THREAD_ERR_CHECK(ret,"pthread_create3");
    for(int i=0;i<3;i++)
    {
        ret=pthread_join(pthid[i],NULL);
        THREAD_ERR_CHECK(ret,"pthread_join");

    }
    printf("main thread tickets=%d\n",d.tickets);
    ret=pthread_mutex_destroy(&d.mutex);
    THREAD_ERR_CHECK(ret,"pthread_mutex_destroy");
    return 0;
    
}